package com.medical.literature.document.service.impl;

import com.medical.literature.document.entity.Keyword;
import com.medical.literature.document.entity.LiteratureKeyword;
import com.medical.literature.document.mapper.DocKeywordMapper;
import com.medical.literature.document.mapper.LiteratureKeywordMapper;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * 关键词处理器
 */
@Service
@RequiredArgsConstructor
public class KeywordProcessor {
    
    // 手动添加log变量
    private static final Logger log = LoggerFactory.getLogger(KeywordProcessor.class);
    
    private final DocKeywordMapper keywordMapper;
    private final LiteratureKeywordMapper literatureKeywordMapper;
    
    /**
     * 处理文献关键词
     * @param literatureId 文献ID
     * @param keywords 关键词列表
     */
    @Transactional
    public void processLiteratureKeywords(Long literatureId, List<String> keywords) {
        try {
            if (keywords == null || keywords.isEmpty()) {
                log.info("文献关键词列表为空，文献ID: {}", literatureId);
                return;
            }
            
            log.info("开始处理文献关键词，文献ID: {}, 关键词数量: {}", literatureId, keywords.size());
            
            // 记录前几个关键词作为示例
            int displayCount = Math.min(5, keywords.size());
            List<String> sampleKeywords = keywords.subList(0, displayCount);
            log.info("示例关键词: {}", sampleKeywords);
            
            for (String keywordText : keywords) {
                if (keywordText == null || keywordText.trim().isEmpty()) {
                    continue;
                }
                
                // 查找或创建关键词
                Keyword keyword = findOrCreateKeyword(keywordText.trim());
                
                // 创建文献关键词关联
                createLiteratureKeywordRelation(literatureId, keyword.getId());
            }
            
            log.info("文献关键词处理完成，文献ID: {}, 关键词数量: {}", literatureId, keywords.size());
            
        } catch (Exception e) {
            log.error("处理文献关键词失败，文献ID: {}", literatureId, e);
            // 不抛出异常，避免影响主流程
        }
    }
    
    /**
     * 查找或创建关键词
     * @param keywordText 关键词文本
     * @return 关键词实体
     */
    private Keyword findOrCreateKeyword(String keywordText) {
        // 查找现有关键词
        com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<Keyword> queryWrapper = 
            new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
        queryWrapper.eq(Keyword::getWord, keywordText);
        
        Keyword existingKeyword = keywordMapper.selectOne(queryWrapper);
        if (existingKeyword != null) {
            // 更新词频
            Keyword updateKeyword = new Keyword();
            updateKeyword.setId(existingKeyword.getId());
            updateKeyword.setFrequency(existingKeyword.getFrequency() + 1);
            keywordMapper.updateById(updateKeyword);
            
            log.debug("更新现有关键词: {}，词频: {}", keywordText, existingKeyword.getFrequency() + 1);
            return existingKeyword;
        }
        
        // 创建新关键词
        Keyword newKeyword = new Keyword();
        newKeyword.setWord(keywordText);
        newKeyword.setFrequency(1);
        newKeyword.setWeight(new BigDecimal("1.0000"));
        keywordMapper.insert(newKeyword);
        
        log.debug("创建新关键词: {}，ID: {}", keywordText, newKeyword.getId());
        return newKeyword;
    }
    
    /**
     * 创建文献关键词关联
     * @param literatureId 文献ID
     * @param keywordId 关键词ID
     */
    private void createLiteratureKeywordRelation(Long literatureId, Long keywordId) {
        // 检查是否已存在关联
        com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<LiteratureKeyword> queryWrapper = 
            new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
        queryWrapper.eq(LiteratureKeyword::getLiteratureId, literatureId)
                   .eq(LiteratureKeyword::getKeywordId, keywordId);
        
        LiteratureKeyword existingRelation = literatureKeywordMapper.selectOne(queryWrapper);
        if (existingRelation != null) {
            log.debug("文献关键词关联已存在，文献ID: {}, 关键词ID: {}", literatureId, keywordId);
            return; // 已存在关联
        }
        
        // 创建新关联
        LiteratureKeyword relation = new LiteratureKeyword();
        relation.setLiteratureId(literatureId);
        relation.setKeywordId(keywordId);
        relation.setWeight(new BigDecimal("1.0000"));
        literatureKeywordMapper.insert(relation);
        
        log.debug("创建文献关键词关联，文献ID: {}, 关键词ID: {}", literatureId, keywordId);
    }
}